package com.bstek.bdf4.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;


@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "jpaEntityManagerFactory",
        transactionManagerRef = "jpaTransactionManager",
        //设置repository所在位置
        basePackages = {"com.bstek.bdf4.investigate.dao"}
)
public class DataSourceConfig {

@Primary
    @Bean("jpaDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ceshi")
    public DataSource dataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        System.out.println("dataSorce=====" + dataSource);
        return dataSource;
    }



    @Primary
    @Bean(name = "jpaEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(JpaUtil.getHibernateJpaVendorAdapter(Database.MYSQL));
        factory.setJpaPropertyMap(JpaUtil.getJpaPropertyMap());
        Properties properties = new Properties();
        // 设置拦截器
//        properties.setProperty("hibernate.ejb.interceptor","com.bstek.dorado.dao.hibernate.UnByteCodeProxyInterceptor");
        properties.setProperty("hibernate.ejb.interceptor","com.bstek.bdf.orm.hibernate.UnByteCodeProxyInterceptor");
        factory.setJpaProperties(properties);
        //设置实体类位置
        factory.setPackagesToScan("com.bstek.bdf4.investigate.entity");
        factory.setDataSource(dataSource());
        return factory;
    }

    @Primary
    @Bean(name = "jpaTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
}